from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, get_object_or_404, render
from django.contrib.auth.models import User
from LogisticsCard.models import UserProfile
from django.utils import timezone

@login_required
def normal_users_view(request):
    """
    用户管理视图，只显示非管理员用户（is_staff=False, is_superuser=False）。
    """
    users = User.objects.filter(is_staff=False, is_superuser=False, 
        profile__type__in=['user'],profile__delete_at__isnull=True)
    return render(request, 'normal_users/index.html', {'users': users})
@login_required
def edit_normal_user_view(request, user_id):
    """
    编辑用户
    """
    from LogisticsCard.models import UserProfile
    user = get_object_or_404(User, id=user_id, is_staff=False, is_superuser=False)
    profile = UserProfile.objects.filter(user=user, delete_at__isnull=True).first()
    if request.method == 'POST':
        user.username = request.POST.get('username')
        user.email = request.POST.get('email')
        user.is_active = request.POST.get('is_active') == 'True'
        user.save()
        if profile:
            profile.realname = request.POST.get('realname')
            profile.save()
        return redirect('/normal_users/')
    return render(request, 'normal_users/edit.html', {'user': user, 'profile': profile})


@login_required
def delete_normal_user_view(request, user_id):
    """
    删除用户
    """
    user = get_object_or_404(User, id=user_id, is_staff=False, is_superuser=False)
    UserProfile.objects.filter(user=user).update(delete_at=timezone.now())
    user.is_active = False
    user.save()
    return redirect('/normal_users/')
